//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useRef, useState } from "react";
import { Button, Card, Dropdown, Empty, Form, List, message, Modal, Popover, Space, Tag } from "antd";
import { useStores } from "@/hooks";
import { observer } from "mobx-react";
import { list as list_shell, exec as exec_shell } from "@/api/shell";
import { get_http_url, set_assistant_mode, set_top, update_repo } from "@/api/local_repo";
import { open as shell_open } from '@tauri-apps/api/shell';
import { EditOutlined, FormatPainterFilled, LoadingOutlined, MoreOutlined } from "@ant-design/icons";
import { openGitAssistant } from "@/utils/git_assistant";
import { isGitFlowInit } from "@/api/git_flow";
import type { LocalRepoExtInfo } from "@/stores/localrepo";
import ConfigGitFlowModal from "./components/localrepo/ConfigGitFlowModal";
import { useHistory } from "react-router-dom";
import LinkProjectModal from "./components/localrepo/LinkProjectModal";
import { APP_PROJECT_HOME_PATH } from "@/utils/constant";
import { EditText } from "@/components/EditCell/EditText";
import { appWindow, WebviewWindow } from "@tauri-apps/api/window";
import { sleep } from "@/utils/time";
import { useTranslation } from "react-i18next";

interface LocalRepoCardProps {
    repo: LocalRepoExtInfo;
    repoIndex: number;
    shellList: string[];
}

const LocalRepoCard = observer((props: LocalRepoCardProps) => {
    const history = useHistory();

    const { t } = useTranslation();

    const userStore = useStores("userStore");
    const projectStore = useStores("projectStore");
    const localRepoStore = useStores("localRepoStore");

    const [removeRepo, setRemoveRepo] = useState(false);
    const [showGitFlowModal, setShowGitFlowModal] = useState(false);
    const [showLinkModal, setShowLinkModal] = useState(false);

    const openGitAnalyse = async (id: string, name: string, path: string) => {
        const label = `gitanalyse:${id.replaceAll("-", "")}`;
        const view = WebviewWindow.getByLabel(label);
        if (view != null) {
            await view.setAlwaysOnTop(true);
            await sleep(500);
            await view.setAlwaysOnTop(false);
            return;
        }

        const pos = await appWindow.innerPosition();

        const view2 = new WebviewWindow(label, {
            url: `git_analyse.html?path=${encodeURIComponent(path)}`,
            width: 1300,
            minWidth: 1300,
            height: 800,
            minHeight: 800,
            title: `代码统计(${name})`,
            resizable: true,
            x: pos.x + Math.floor(Math.random() * 200),
            y: pos.y + Math.floor(Math.random() * 200),
        });
        console.log(label, view2);

    };

    return (
        <Card title={
            <EditText editable content={props.repo.repoInfo.name} showEditIcon
                width="110px"
                onChange={async value => {
                    if (value.trim() == "") {
                        return false;
                    }
                    try {
                        await update_repo(props.repo.id, value.trim(), props.repo.repoInfo.path, props.repo.repoInfo.color ?? '#FF6900');
                        await localRepoStore.onUpdateRepoName(props.repo.id, value.trim());
                        return true;
                    } catch (e) {
                        console.log(e);
                    }
                    return false;
                }} />
        } headStyle={{ fontSize: "20px", backgroundColor: "#eee" }}
            style={{ width: "290px", boxShadow: "10px 10px 10px 0px #777" }} bodyStyle={{ height: "280px", backgroundColor: props.repo.repoInfo.color ?? '#FF6900' }}
            extra={
                <Space>
                    <Button type="text" icon={<FormatPainterFilled />} onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        const colorList = ['#FF6900', '#FCB900', '#7BDCB5', '#00D084', '#8ED1FC', '#0693E3', '#ABB8C3', '#EB144C', '#F78DA7', '#9900EF'];
                        const index = Math.floor(Math.random() * colorList.length);
                        update_repo(props.repo.id, props.repo.repoInfo.name, props.repo.repoInfo.path, colorList[index]).then(() => {
                            localRepoStore.onUpdateRepoColor(props.repo.id, colorList[index]);
                        });
                    }} />
                    {props.repo.filterList.map(filter => (
                        <Tag key={filter} style={{ backgroundColor: "#ddd", fontSize: "20px", fontWeight: 700, padding: "2px 8px" }}>{filter}</Tag>
                    ))}
                    <Popover placement="bottom" trigger="click" content={
                        <Space direction="vertical">
                            <Button type="link" disabled={props.repoIndex == 0}
                                onClick={e => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    set_top(props.repo.id).then(() => localRepoStore.loadRepoList());
                                }}>置顶</Button>
                            <Button type="link" danger onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setRemoveRepo(true);
                            }}>删除</Button>
                        </Space>
                    }>
                        <MoreOutlined />
                    </Popover>
                </Space>
            }>
            <Form labelCol={{ span: 6 }}>
                <Form.Item label={t("text.localDir")} style={{ marginBottom: "2px" }}>
                    <a style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", width: "210px", display: "inline-block" }} onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        shell_open(props.repo.repoInfo.path);
                    }} title={props.repo.repoInfo.path}>{props.repo.repoInfo.path}</a>
                </Form.Item>
                {props.repo.headInfo.detached == false && (
                    <Form.Item label={t("text.curBranch")} style={{ marginBottom: "2px" }}>
                        {props.repo.headInfo.branch_name}
                    </Form.Item>
                )}
                {props.repo.headInfo.detached == true && props.repo.headInfo.tag_name != "" && (
                    <Form.Item label={t("text.curTag")} style={{ marginBottom: "2px" }}>
                        {props.repo.headInfo.tag_name}
                    </Form.Item>
                )}

                <Form.Item label={t("text.remoteUrl")} style={{ marginBottom: "2px" }}>
                    {props.repo.remoteList.filter(remote => remote.name == "origin").map(remote => (
                        <a key={remote.name} style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", width: "210px", display: "inline-block" }} onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            shell_open(get_http_url(remote.url));
                        }} title={remote.url}>({remote.name}){remote.url}</a>
                    ))}
                </Form.Item>
                {userStore.sessionId != "" && userStore.userInfo.featureInfo.enable_project && (
                    <Form.Item label={t("text.relateProject")} style={{ marginBottom: "2px" }}>
                        {props.repo.projectId == "" && (
                            <Space>
                                <span>未关联项目</span>
                                <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }} onClick={e => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    setShowLinkModal(true);
                                }} icon={<EditOutlined />} />
                            </Space>
                        )}
                        {props.repo.projectId != "" && projectStore.getProject(props.repo.projectId) != undefined && (
                            <Space>
                                <a onClick={e => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    projectStore.setCurProjectId(props.repo.projectId);
                                    history.push(APP_PROJECT_HOME_PATH);
                                }}>{projectStore.getProject(props.repo.projectId)?.basic_info.project_name ?? ""}</a>
                                <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }} onClick={e => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    setShowLinkModal(true);
                                }} icon={<EditOutlined />} />
                            </Space>
                        )}
                        {props.repo.projectId != "" && projectStore.getProject(props.repo.projectId) == undefined && (
                            <Space>
                                <span>已关联到其他项目</span>
                                <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }} onClick={e => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    setShowLinkModal(true);
                                }} icon={<EditOutlined />} />
                            </Space>
                        )}
                    </Form.Item>
                )}

                <Form.Item label={t("text.workflow")} style={{ marginBottom: "2px" }}>
                    <a onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setShowGitFlowModal(true);
                    }}>{isGitFlowInit(props.repo.branchList, props.repo.gitFlowInfo) ? t("text.opened") : t("text.notOpen")}</a>
                </Form.Item>
                <Form.Item label={t("text.openBy")}>
                    <Space style={{ flexWrap: "wrap" }}>
                        <Dropdown.Button type="primary" menu={{
                            items: [
                                {
                                    label: t("text.simpleMode"),
                                    key: "simple"
                                },
                                {
                                    label: t("text.expertMode"),
                                    key: "expert"
                                }
                            ],
                            onClick: menuInfo => {
                                if (["simple", "expert"].includes(menuInfo.key)) {
                                    set_assistant_mode(menuInfo.key as "simple" | "expert").then(
                                        () => openGitAssistant(props.repo.repoInfo, userStore.userInfo.userName, userStore.userInfo.userType, userStore.userInfo.extraToken)
                                    );
                                }
                            },
                        }} onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            openGitAssistant(props.repo.repoInfo, userStore.userInfo.userName, userStore.userInfo.userType, userStore.userInfo.extraToken);
                        }}>
                            {t("text.gitAssistant")}
                        </Dropdown.Button>
                        <Button type="default" onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            openGitAnalyse(props.repo.id, props.repo.repoInfo.name, props.repo.repoInfo.path);
                        }}>{t("text.codestatistics")}</Button>
                        <Button type="default" onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            shell_open(props.repo.repoInfo.path);
                        }}>{t("text.fileExplorer")}</Button>
                        {props.shellList.map(shell => (
                            <Button key={shell} type="default" onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                exec_shell(shell, props.repo.repoInfo.path);
                            }}>{shell}</Button>
                        ))}
                    </Space>
                </Form.Item>
            </Form>
            {removeRepo && (
                <Modal open title="删除本地仓库" mask={false}
                    okText="删除" okButtonProps={{ danger: true }}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setRemoveRepo(false);
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        localRepoStore.removeRepo(props.repo.id);
                        setRemoveRepo(false);
                        message.info("删除成功");
                    }}>
                    是否删除本地仓库&nbsp;{props.repo.repoInfo.name}&nbsp;?
                </Modal>
            )}
            {showGitFlowModal && (
                <ConfigGitFlowModal repoExtInfo={props.repo} onClose={() => setShowGitFlowModal(false)} />
            )}
            {showLinkModal && (
                <LinkProjectModal repoExtInfo={props.repo} onClose={() => setShowLinkModal(false)} />
            )}
        </Card>
    );
});

const LocalRepoList = () => {
    const localRepoStore = useStores("localRepoStore");

    const firstItemRef = useRef<HTMLDivElement>(null);

    const [shellList, setShellList] = useState([] as string[]);

    useEffect(() => {
        localRepoStore.init();
        list_shell().then(res => setShellList(res));
    }, []);

    useEffect(() => {
        if (firstItemRef.current != null) {
            firstItemRef.current?.scrollIntoView();
        }
    }, [firstItemRef.current]);

    return (
        <>
            {localRepoStore.inInit && (
                <Empty image={<LoadingOutlined />} imageStyle={{ fontSize: "60px" }} description="加载本地仓库数据" />
            )}
            {localRepoStore.inInit == false && (
                <List rowKey="id" dataSource={localRepoStore.repoExtList} grid={{ gutter: 16 }}
                    style={{ height: "calc(100vh - 235px)", overflowY: "scroll", overflowX: "hidden" }}
                    pagination={false} renderItem={(repo, repoIndex) => (
                        <List.Item ref={repoIndex == 0 ? firstItemRef : undefined}>
                            <LocalRepoCard repo={repo} repoIndex={repoIndex} shellList={shellList} />
                        </List.Item>
                    )} />
            )}

        </>
    );
}

export default observer(LocalRepoList);